<template>
  <div>
    <!-- 面包屑到导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-alert
      title="添加商品信息"
      type="info"
      center
      show-icon
      :closable="false"
    >
    </el-alert>
    <!-- 步骤条区域 -->
    <div class="mainBox">
      <el-steps :active="activeIndex - 0" align-center direction="vertical">
        <el-step title="spu信息"></el-step>
        <el-step title="sku信息"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addGoodsForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="120px"
        label-suffix="："
      >
        <el-tabs
          :tab-position="tabPosition"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="handleTabClick"
        >
          <el-tab-pane label="spu信息" name="0">
            <div class="shuxingBox">
              <el-form-item label="商品分类" prop="categoryId">
                <el-cascader
                  v-model="addGoodsForm.categoryId"
                  :options="cateList"
                  :props="cateProps"
                  @change="handleChangeDialog"
                  clearable
                ></el-cascader>
              </el-form-item>
              <el-form-item label="SPU名称" prop="name">
                <el-input
                  v-model="addGoodsForm.name"
                  placeholder="请输入SPU名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="折扣类型" prop="discountType">
                <template>
                  <el-select
                    v-model="addGoodsForm.discountType"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in optionDiscount"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>
              </el-form-item>
              <el-form-item label="折扣值" prop="discountValue">
                <el-input v-model="addGoodsForm.discountValue"></el-input>
              </el-form-item>
              <el-form-item label="设计师" prop="designer">
                <el-select v-model="addGoodsForm.designer" placeholder="请选择">
                  <el-option
                    v-for="item in designerList"
                    :label="item.name"
                    :value="item.name"
                    :key="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="材质" prop="material">
                <el-input
                  v-model="addGoodsForm.material"
                  placeholder="请输入材质"
                ></el-input>
              </el-form-item>
              <el-form-item label="设计理念" prop="designConcept">
                <el-input
                  v-model="addGoodsForm.designConcept"
                  placeholder="请输入设计理念"
                  type="textarea"
                  rows="1"
                ></el-input>
              </el-form-item>
              <el-form-item label="保养说明" prop="maintain">
                <el-input
                  v-model="addGoodsForm.maintain"
                  placeholder="请输入保养说明"
                  type="textarea"
                  rows="1"
                ></el-input>
              </el-form-item>
              <el-form-item label="推荐指数" prop="score">
                <el-rate v-model="addGoodsForm.score"></el-rate>
              </el-form-item>
              <el-form-item> </el-form-item>
              <el-form-item label="SPU默认图片">
                <div class="uploadBox">
                  <el-upload
                    action=""
                    ref="defaultImgRef"
                    list-type="picture-card"
                    :limit="1"
                    :http-request="spuDefaultImageUpload"
                    :before-upload="imageBeforeUpload"
                  >
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{ file }">
                      <img
                        class="el-upload-list__item-thumbnail"
                        :src="file.url"
                        alt=""
                      />
                      <span class="el-upload-list__item-actions">
                        <span
                          class="el-upload-list__item-preview"
                          @click="defaultImgPreview(file)"
                        >
                          <i class="el-icon-zoom-in"></i>
                        </span>
                        <span
                          v-if="!disabled"
                          class="el-upload-list__item-delete"
                          @click="defaultImgRemove(file)"
                        >
                          <i class="el-icon-delete"></i>
                        </span>
                      </span>
                    </div>
                  </el-upload>
                  <el-dialog :visible.sync="defaultDialogVisible">
                    <img width="100%" :src="ImgsPre" alt="" />
                  </el-dialog>
                </div>
              </el-form-item>
              <el-form-item label="SPU图片集">
                <div class="uploadBox">
                  <el-upload
                    action=""
                    ref="spuImgsRef"
                    list-type="picture-card"
                    :http-request="spuImageListUpload"
                    :before-upload="imageBeforeUpload"
                  >
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{ file, fileList }">
                      <img
                        class="el-upload-list__item-thumbnail"
                        :src="file.url"
                        alt=""
                      />
                      <span class="el-upload-list__item-actions">
                        <span
                          class="el-upload-list__item-preview"
                          @click="spuImgsPreview(file)"
                        >
                          <i class="el-icon-zoom-in"></i>
                        </span>
                        <span
                          v-if="!disabled"
                          class="el-upload-list__item-delete"
                          @click="spuImgsRemove(file, fileList)"
                        >
                          <i class="el-icon-delete"></i>
                        </span>
                      </span>
                    </div>
                  </el-upload>
                  <el-dialog :visible.sync="spuImgsDialogVisible">
                    <img width="100%" :src="ImgsPre" alt="" />
                  </el-dialog>
                </div>
              </el-form-item>
              <el-form-item label="SPU描述" label-width="100px">
                <quill-editor
                  v-model="addGoodsForm.description"
                  style="width: 1000px"
                ></quill-editor>
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="sku信息" name="1">
            <el-empty v-if="!showtable">
              <el-button
                type="primary"
                @click="addSKUInfo(addGoodsForm.skuList.length)"
                size="small"
                >添加SKU属性
              </el-button>
            </el-empty>
            <div class="tableBox" v-if="showtable">
              <el-table :data="addGoodsForm.skuList" style="width: 100%" border>
                <el-table-column label="sku名称" prop="name" align="center">
                </el-table-column>
                <el-table-column label="商品价格" prop="price" align="center">
                </el-table-column>
                <el-table-column
                  label="sku描述"
                  prop="description"
                  show-overflow-tooltip
                  align="center"
                >
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <!-- 编辑按钮 -->
                    <el-button
                      type="error"
                      icon="el-icon-edit"
                      size="mini"
                      @click="editSkuInfo(scope.row)"
                    ></el-button>
                    <el-button
                      type="primary"
                      icon="el-icon-delete"
                      size="mini"
                      @click="dropSkuListItem(scope.row)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="tableBtnBox">
                <el-button
                  type="primary"
                  size="small"
                  @click="addSKUInfo(addGoodsForm.skuList.length)"
                  >继续添加</el-button
                >
                <el-button type="success" size="small" @click="saveGoods"
                  >保存</el-button
                >
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
    <!-- sku属性抽屉 -->
    <el-drawer
      :visible.sync="skuDrawer"
      width="100"
      :direction="skuDrawerDriection"
      :before-close="skuDrawerClose"
    >
      <div class="skubox" v-if="skuDrawer">
        <div class="containerbox">
          <h3>添加SKU属性</h3>
        </div>
        <div class="formBox">
          <el-form
            :model="addGoodsForm.skuList[skuInfoIndex]"
            :rules="skuFormRules"
            ref="addskuRef"
            label-width="120px"
            class="demo-ruleForm"
          >
            <el-form-item label="SKU名称" prop="name">
              <el-input
                v-model="addGoodsForm.skuList[skuInfoIndex].name"
              ></el-input>
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input
                v-model="addGoodsForm.skuList[skuInfoIndex].price"
              ></el-input>
            </el-form-item>
            <el-form-item label="重量" prop="weight">
              <el-input
                v-model="addGoodsForm.skuList[skuInfoIndex].weight"
              ></el-input>
            </el-form-item>
            <el-form-item label="长度" prop="length">
              <el-input
                v-model="addGoodsForm.skuList[skuInfoIndex].length"
              ></el-input>
            </el-form-item>
            <el-form-item label="宽度" prop="width">
              <el-input
                v-model="addGoodsForm.skuList[skuInfoIndex].width"
              ></el-input>
            </el-form-item>
            <el-form-item label="高度" prop="height">
              <el-input
                v-model="addGoodsForm.skuList[skuInfoIndex].height"
              ></el-input>
            </el-form-item>
            <el-form-item label="数量" prop="inventory">
              <el-input
                v-model="addGoodsForm.skuList[skuInfoIndex].inventory"
              ></el-input>
            </el-form-item>
            <el-form-item></el-form-item>
            <el-form-item label="sku默认图片">
              <div class="uploadBox">
                <el-upload
                  action=""
                  ref="skuDefaultImgRef"
                  list-type="picture-card"
                  :limit="1"
                  :http-request="skuDefaultImageUpload"
                  :before-upload="imageBeforeUpload"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{ file }">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="skuDefaultImgPreview(file)"
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="skuDefaultImgRemove(file)"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
                <el-dialog :visible.sync="skuDefaultDialogVisible">
                  <img width="100%" :src="ImgsPre" alt="" />
                </el-dialog>
              </div>
            </el-form-item>
            <el-form-item label="sku图片集" prop="discountValue">
              <div class="uploadBox">
                <el-upload
                  action=""
                  ref="skuImgsRef"
                  list-type="picture-card"
                  :http-request="skuImageListUpload"
                  :before-upload="imageBeforeUpload"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{ file }">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="skuImgsPreview(file)"
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="skuImgsRemove(file)"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
                <el-dialog :visible.sync="skuImgsDialogVisible">
                  <img width="100%" :src="ImgsPre" alt="" />
                </el-dialog>
              </div>
            </el-form-item>
            <el-form-item label="SKU描述" style="width: 1000px">
              <div class="skudesc">
                <quill-editor
                  style="width: 1160px; height: 260px"
                  v-model="addGoodsForm.skuList[skuInfoIndex].description"
                ></quill-editor>
              </div>
              <div class="btnbox">
                <el-button type="primary" size="medium" @click="savaSkuInfo"
                  >保存
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      optionDiscount: [
        { label: '打折', value: 'percentage' },
        { label: '优惠券', value: 'coupon' },
      ],
      designerList: [
        { name: 'John Deo', id: '0' },
        { name: 'Adeline Adele', id: '1' },
        { name: 'YiNnuo Li', id: '2' },
        { name: 'LiGang', id: '3' },
      ],
      queryInfo: {
        type: 3,
        curPage: 1,
        pagesSize: 5,
      },
      // 图片预览的url地址
      ImgsPre: '',
      // 商品分类列表
      cateList: [],
      // 动态参数数组
      cateProps: {
        label: 'name',
        value: 'serialNo',
        children: 'children',
      },
      defaultDialogVisible: false,
      spuImgsDialogVisible: false,
      skuDefaultDialogVisible: false,
      skuImgsDialogVisible: false,
      skuDrawer: false,
      disabled: false,
      skuDrawerDriection: 'rtl',
      activeIndex: 0,
      tabPosition: 'top',
      // 添加商品的表单对象
      addGoodsForm: {
        serialNo: '',
        // SPU名称
        name: '',
        // 分类编号,级联选择框绑定是数组
        categoryId: [],
        // 设计者
        designer: '',
        // 设计理念
        designConcept: '',
        // 保养说明
        maintain: '',
        // 默认图片
        defaultImage: '',
        // 材质
        material: '',
        // 折扣类型
        discountType: '',
        // 折扣值
        discountValue: '',
        // sku图片集
        imageList: [],
        // sku列表
        skuList: [],
        // 描述
        description: '',
        // 备注
        extra: '',
        score: '',
      },
      addFormrules: {
        name: [{ required: true, message: '请输入SPU名称', trigger: 'blur' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ],
      },
      skuFormRules: {
        name: [{ required: true, message: '请输入SKU名称', trigger: 'blur' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        length: [
          { required: true, message: '请输入商品长度', trigger: 'blur' },
        ],
        height: [
          { required: true, message: '请输入商品高度', trigger: 'blur' },
        ],
        inventory: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
      },
      total: 0,
      totalPage: 0,
      imageFileTmpFormData: new FormData(),
      skuInfoIndex: 0,
    }
  },
  watch: {
    $route(to, from) {
      console.log(from)
    },
  },
  activated() {
    this.init()
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    init() {
      let serialNo = this.$route.params.spuNo
      if (serialNo) {
        this.$http({
          url: this.$http.adornUrl(`/mall/spuinfo/info/${serialNo}`),
          method: 'post',
        }).then((res) => {
          console.log(res)
          if (res.data.code === 0) {
            this.addGoodsForm = res.data.spuInfo
          }
          console.log(this.addGoodsForm)
        })
      }
    },
    // 获取分类列表
    getCategoryList() {
      this.$http({
        url: this.$http.adornUrl('/mall/categoryinfo/tree'),
        method: 'get',
        params: this.$http.adornParams({
          page: this.queryInfo.curPage,
          limit: this.queryInfo.pagesSize,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.cateList = data.page.list
        } else {
          this.cateList = []
        }
      })
    },
    handleTabClick() {},
    // 级联选择器选择项的变换监听
    handleChangeDialog(value) {
      console.log(this.addGoodsForm.categoryId)
    },
    // 跳转到sku页面
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodsForm.categoryId.length === 0) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // spu图片集删除
    spuImgsRemove(file, fileList) {
      console.log(file, fileList)
      this.$refs.spuImgsRef.clearFiles()
    },
    // sku图片集删除
    skuImgsRemove(file) {
      this.$refs.skuImgsRef.clearFiles()
    },
    // spu默认图片预览图片
    defaultImgPreview(file) {
      this.ImgsPre = file.url
      this.defaultDialogVisible = true
    },
    // sku默认图片预览图片
    skuDefaultImgPreview(file) {
      this.ImgsPre = file.url
      this.skuDefaultDialogVisible = true
    },
    // spu图片集预览图片
    spuImgsPreview(file) {
      this.ImgsPre = file.url
      this.spuImgsDialogVisible = true
    },
    // sku图片集预览图片
    skuImgsPreview(file) {
      this.ImgsPre = file.url
      this.skuImgsDialogVisible = true
    },
    // sku默认图片删除
    skuDefaultImgRemove() {
      this.$refs.skuDefaultImgRef.clearFiles()
    },
    // spu默认图片移除图片
    defaultImgRemove() {
      console.log(this.$refs.defaultImgRef)
      this.$refs.defaultImgRef.clearFiles()
    },
    // 添加所有的属性给商品
    addGoodsBtn() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('填写完整的表单项')
        }
        // 执行合法操作
        // 改造表单数据 对数据categoryId进行深拷贝 借助lodsh 方法 cloneDeep方法
        const form = _.cloneDeep(this.addGoodsForm)
        form.categoryId = form.categoryId.join(',')
        console.log(form)
      })
    },
    // 添加sku属性
    addSKUInfo(index) {
      this.skuDrawer = true
      this.addGoodsForm.skuList.push({
        serialNo: '',
        spuNo: '',
        name: '',
        displayName: '',
        description: '',
        defaultImg: '',
        price: 0,
        weight: 0,
        length: 0,
        width: 0,
        height: 0,
        inventory: 0,
        imageList: [],
      })
      // 让抽屉的表单绑定到sku_info的sku_list的新增项即可
      // 但是依然考虑到新增玩编辑的问题，应该以序号为参数进行绑定
      this.skuInfoIndex = index
    },
    // 保存添加的sku属性
    savaSkuInfo() {
      this.$refs.addskuRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('填写完整的表单项')
        }
        this.skuDrawer = !this.skuDrawer
      })
    },
    skuDrawerClose() {
      // 抽屉关闭时如果没有输入信息的话，也就是主动调用一次表单校验，通过就不把当前的skuIndex的元素删除；不通过提示，执意退出就删除
      this.$refs.addskuRef.resetFields()
      this.skuDrawer = !this.skuDrawer
    },
    imageBeforeUpload(file) {
      if (file) {
        console.log(file)
        this.imageFileTmpFormData.set('file', file)
      } else {
        return false
      }
    },
    skuDefaultImageUpload() {
      this.imageUpload().then(({ data }) => {
        if (data.code === 0) {
          this.addGoodsForm.skuList[this.skuInfoIndex].defaultImg = data.url
        }
      })
    },
    skuImageListUpload() {
      this.imageUpload().then(({ data }) => {
        if (data.code === 0) {
          this.addGoodsForm.skuList[this.skuInfoIndex].imageList.push({
            imgUrl: data.url,
          })
        }
      })
    },
    spuDefaultImageUpload() {
      this.imageUpload().then(({ data }) => {
        if (data.code === 0) {
          this.addGoodsForm.defaultImage = data.url
        }
      })
    },
    spuImageListUpload() {
      this.imageUpload().then(({ data }) => {
        console.log(data)
        if (data.code === 0) {
          this.addGoodsForm.imageList.push({
            imgUrl: data.url,
          })
        }
      })
    },
    // 上传图片
    imageUpload() {
      // 使用axios上传图片，如此携带token以及使用axios拦截器
      return this.$http({
        url: this.$http.adornUrl('/sys/oss/upload'),
        method: 'post',
        data: this.imageFileTmpFormData,
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
    },
    saveGoods() {
      // 处理原数据中的categoryId,因为element-ui绑定的是数组....
      let saveGoodsInfo = _.cloneDeep(this.addGoodsForm)
      let length = saveGoodsInfo.categoryId.length
      saveGoodsInfo.categoryId = saveGoodsInfo.categoryId[length - 1]
      console.log(saveGoodsInfo)
      if (saveGoodsInfo.serialNo) {
        this.$http({
          url: this.$http.adornUrl('/mall/spuinfo/update'),
          method: 'post',
          data: this.$http.adornData(saveGoodsInfo),
        }).then((res) => {
          console.log(res)
          if (res.data.code !== 0) {
            this.$message.error(res.data.msg)
            return false
          }
          this.$message.success('修改成功')
          window.location.reload()
          this.skuDrawer = false
        })
      } else if (saveGoodsInfo.serialNo === '') {
        this.$http({
          url: this.$http.adornUrl('/mall/spuinfo/save'),
          method: 'post',
          data: this.$http.adornData(saveGoodsInfo),
        }).then((res) => {
          console.log(res)
          if (res.data.code !== 0) {
            this.$message.error(res.data.msg)
            return false
          }
          this.$message.success('添加成功')
          window.location.reload()
          this.skuDrawer = false
        })
      }
    },
    editSkuInfo(item) {
      let pos = this.addGoodsForm.skuList.indexOf(item)
      this.addGoodsForm.skuList[pos] = item
      this.skuDrawer = true
    },
    // 删除某个sku信息
    dropSkuListItem(item) {
      let msg = '你确定要删除本条sku信息?'
      // 弹出一个框，用来提示用户是否确定删除
      this.$confirm(msg, '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      })
        .then(() => {
          let pos = this.addGoodsForm.skuList.indexOf(item)
          this.addGoodsForm.skuList.splice(pos, 1)
        })
        .catch(() => {
          console.log('cancel')
        })
    },
  },
  computed: {
    showtable() {
      if (this.addGoodsForm.skuList.length === 0) {
        return false
      } else return true
    },
  },
}
</script>
<style lang="scss">
.el-alert {
  margin: 20px 0;
}

.mainBox {
  display: flex;

  .el-steps {
    width: 10%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 800px;
    padding: 100px 0;
  }

  .el-form {
    flex: 1;
    border-left: 1px solid #f5f5f5;
  }
}

.el-form {
  .el-tabs {
    .el-tab-pane {
      border-top: 1px solid #f5f5f5;
      padding-top: 20px;

      .textBoxA {
        margin: 0 0 20px 0;
      }

      .ql-editor {
        height: 400px;
      }

      .shuxingBox {
        display: flex;
        flex-wrap: wrap;

        .el-form-item {
          width: 500px;

          .el-select {
            width: 300px;
          }

          .el-input {
            width: 300px;
          }

          .el-textarea {
            width: 300px;
          }

          .uploadBox {
            width: 500px;
            display: flex;
          }
          .el-rate {
            margin-top: 10px;
          }
        }
      }

      .addbtnBox {
        width: 80%;
        text-align: left;
      }

      .tableBox {
        margin: 10px 0;

        .tableBtnBox {
          margin: 20px 0;
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }
}

.el-drawer__wrapper {
  .rtl {
    width: 100% !important;

    .skubox {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .containerbox {
        display: flex;
        align-items: center;
        flex-direction: column;
      }

      .formBox {
        width: 1460px;
        display: flex;
        margin: 20px;

        .el-form {
          display: flex;
          justify-content: center;
          flex-wrap: wrap;

          .el-form-item {
            width: 500px;
            margin: 20px 0;

            .el-select {
              width: 380px;
            }

            .uploadBox {
              width: 500px;
              display: flex;
            }

            .skudesc {
              margin: 0 0 60px 0;
            }
          }
        }
      }
    }
  }
}
</style>
